<?php

namespace app\controller\teacher;

use app\BaseController;
use app\Code;
use app\dao\TrainingDao;
use app\validate\TrainingValidate;
use think\exception\ValidateException;
use think\facade\Request;
use think\facade\Log;


class TrainingController extends BaseController
{
    // 创建训练任务
    public function createTask()
    {
        $data = Request::post();
        $teacherId = session('user_id');

        try {
            validate(TrainingValidate::class)->scene('create')->check($data);
        } catch (ValidateException $e) {
            return json(['code' => 422, 'msg' => $e->getMessage()]);
        }

        try {
            // 验证字段
            validate(TrainingValidate::class)->check($data);

            $task = TrainingDao::createTask(
                $data['project_id'],
                $data['title'],
                $data['content'],
                $data['start_time'],
                $data['end_time']
            );

            Log::info("教师 {$teacherId} 创建了一个新的训练任务");

            return $this->returnJson($task);
        }catch (ValidateException $e) {

            return $this->returnJson([], Code::SERVER_ERROR, $e->getMessage());

        } catch (\Exception $e) {
            Log::error("创建训练任务失败: " . $e->getMessage());
            return $this->returnJson([],Code::SERVER_ERROR, '服务器错误，请稍后再试');
        }
    }
}
